package org.openwebtop.sunshine.interceptors;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.commons.lang.time.DateUtils;
import org.openwebtop.sunshine.constants.GlobalConstants;
import org.openwebtop.sunshine.user.UserContext;
import org.openwebtop.sunshine.user.UserContextAware;
import org.openwebtop.sunshine.util.GlobalContext;

import com.opensymphony.xwork.ActionInvocation;
import com.opensymphony.xwork.interceptor.Interceptor;

@SuppressWarnings("serial")
public class UserContextInterceptor implements Interceptor {
	private final static String LOGIN_TIMEOUT = "login_timeout";
	private final static UserContext NOT_LOGINED_USERCONTEXT = new UserContext(null);
	private final static int LOGIN_TIMEOUT_SECONDS = 300;

	public void init() {
	}

	public void destroy() {
	}

	public String intercept(ActionInvocation invocation) throws Exception {
		final Object obj = invocation.getAction();

		if (obj instanceof UserContextAware) {
			final UserContextAware action = (UserContextAware)obj;
			final UserContext userContext = (UserContext)GlobalContext.getAttribute(GlobalConstants.USER_CONTEXT_KEY);

			if (userContext != null && userContext.isLogin()) {
				if (checkLoginTimeout(userContext)) {
					GlobalContext.setAttribute(GlobalConstants.USER_CONTEXT_KEY, null);

					return LOGIN_TIMEOUT;
				}

				final Calendar calendar = new GregorianCalendar();
				userContext.setLastAccessDate(calendar.getTime());

				action.setUserContext(userContext);
			} else {
				action.setUserContext(NOT_LOGINED_USERCONTEXT);
			}
		}

		return invocation.invoke();
	}

	private boolean checkLoginTimeout(UserContext userContext) {
		if (userContext != null) {
			final Calendar calendar = new GregorianCalendar();
			final Date timeoutDate = DateUtils.addSeconds(userContext.getLastAccessDate(), LOGIN_TIMEOUT_SECONDS);

			return timeoutDate.before(calendar.getTime());
		}

		return false;
	}

}
